﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KZ.Express.H.Presenter;
using KZ.Express.H.ENT;
using KZ.Utilities;
using KZ.Express.H.CustomControl;

namespace KZ.Express.H.Orders
{
    public partial class SaleOrderListView : BaseView, IOrderListView
    {
        #region Fields

        object _preValue;
        List<DataRow> _changedRow;

        #endregion

        #region Private Methods

        private void SaleOrderListView_Load(object sender, EventArgs e)
        {
            _changedRow = new List<DataRow>();

            this.dtpFrom.Value = DateTime.Today.AddDays(-7);
            this.dtpTo.Value = DateTime.Today;
            this.toolTip1.SetToolTip(this.txtWeight, ">={Số ký}\n>{Số ký}\n<={Số ký}\n<{Số ký}\n{Từ số ký}-{Đến số ký}");

            LoadCountry();
            LoadCarrier();
            LoadSupplier();
        }

        private void dtgOrder_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            _preValue = dtgOrder[e.ColumnIndex, e.RowIndex].Value;
        }

        private void dtgOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (Utility.DecimalNParse(_preValue) == Utility.DecimalNParse(dtgOrder[e.ColumnIndex, e.RowIndex].Value))
                return;

            SaleOrderPresenter presenter = _presenter as SaleOrderPresenter;

            if (e.ColumnIndex == colListPrice.Index)
                presenter.UpdateListPrice();
            else if (e.ColumnIndex == colFuel.Index)
                presenter.UpdateFuel();
            else if (e.ColumnIndex == colVAT.Index)
                presenter.UpdateVAT();

            presenter.AddChangedRow();
        }

        private void dtgOrder_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.ColumnIndex != -1 && e.RowIndex != -1)
            {
                if (_preValue == null || Convert.IsDBNull(_preValue))
                    dtgOrder[e.ColumnIndex, e.RowIndex].Value = DBNull.Value;
                else
                    dtgOrder[e.ColumnIndex, e.RowIndex].Value = _preValue;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            _changedRow.Clear();
            string weight = this.txtWeight.Text.Trim();
            if (String.IsNullOrWhiteSpace(weight))
            {
                this.FromWeight = null;
                this.ToWeight = null;
            }
            else
            {
                if (weight.StartsWith(">="))
                {
                    this.FromWeight = Utility.DecimalParse(weight.Replace(">=", String.Empty).Trim());
                    this.ToWeight = 9999;
                }
                else if (weight.StartsWith(">"))
                {
                    this.FromWeight = Utility.DecimalParse(weight.Replace(">", String.Empty).Trim()) + 0.1M;
                    this.ToWeight = 9999;
                }
                else if (weight.StartsWith("<="))
                {
                    this.ToWeight = Utility.DecimalParse(weight.Replace("<=", String.Empty).Trim());
                    this.FromWeight = 0;
                }
                else if (weight.StartsWith("<"))
                {
                    this.ToWeight = Utility.DecimalParse(weight.Replace("<", String.Empty).Trim()) - 0.1M;
                    this.FromWeight = 0;
                }
                else if (weight.Split('-').Length == 2)
                {
                    string[] tmp = weight.Split('-');
                    this.FromWeight = Utility.DecimalNParse(tmp[0].Trim());
                    this.ToWeight = Utility.DecimalNParse(tmp[1].Trim());
                }
                else
                    this.FromWeight = this.ToWeight = Utility.DecimalNParse(weight);
            }
            LoadData<SaleOrderENT>();
        }

        private void btnViewAll_Click(object sender, EventArgs e)
        {
            _changedRow.Clear();
            this.Search = null;
            this.FromWeight = null;
            this.ToWeight = null;
            this.txtWeight.Clear();
            LoadData<SaleOrderENT>();
        }

        private void LoadCountry()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<CountryENT>(null);
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbCountryID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void LoadCarrier()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<CarrierENT>(null);
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbCarrierID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        private void LoadSupplier()
        {
            try
            {
                DataTable dt = _presenter.LoadDataTable<SupplierENT>(null);
                dt.Rows.InsertAt(dt.NewRow(), 0);
                this.cmbSupplierID.DataSource = dt;
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        #endregion

        #region Constructors

        public SaleOrderListView()
        {
            InitializeComponent();
            Initialize(this.dtgOrder);

            _presenter = new SaleOrderPresenter(this);

            this.ObjectID = (int)Objects.CSOrder;
            this.ActionName = "ListWithSaveFuelNotDelete";
            this.VisibleChanged += new EventHandler(View_VisibleChanged<SaleOrderENT>);
            this.dtgOrder.Sorted += new EventHandler(Datagrid_Sorted);
            this.OnDeleteClick += new DeleteClickHandler(View_OnDeleteClick<SaleOrderENT>);

            Global.SetDoubleBuffered(dtgOrder);
        }

        #endregion

        #region Public Properties

        [Search]
        public int SaleID
        {
            get { return UserENT._USERID; }
        }

        public int OrderID
        {
            get { return Utility.IntParse(dtgOrder[colOrderID.Index, dtgOrder.CurrentCell.RowIndex].Value); }
        }

        [Search]
        public DateTime From
        {
            get { return dtpFrom.Value; }
            set
            {
                if (value != DateTime.MinValue)
                    dtpFrom.Value = value;
            }
        }

        [Search]
        public DateTime To
        {
            get { return dtpTo.Value; }
            set
            {
                if (value != DateTime.MinValue)
                    dtpTo.Value = value;
            }
        }

        [Search]
        public string CustomerName
        {
            get { return txtCustomerName.Text.Trim(); }
            set { txtCustomerName.Text = value; }
        }

        [Search]
        public decimal? FromWeight { get; set; }

        [Search]
        public decimal? ToWeight { get; set; }

        [Search]
        public int? CountryID
        {
            get { return Utility.IntNParse(cmbCountryID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbCountryID.SelectedValue = value;
                else
                    cmbCountryID.SelectedValue = DBNull.Value;
            }
        }

        [Search]
        public string OrderNumber
        {
            get { return txtOrderNumber.Text.Trim(); }
            set { txtOrderNumber.Text = value; }
        }

        [Search]
        public string MasterOrderNumber
        {
            get { return txtMasterOrderNumber.Text.Trim(); }
            set { txtMasterOrderNumber.Text = value; }
        }

        [Search]
        public int? CarrierID
        {
            get { return Utility.IntNParse(cmbCarrierID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbCarrierID.SelectedValue = value;
                else
                    cmbCarrierID.SelectedValue = DBNull.Value;
            }
        }

        [Search]
        public int? SupplierID
        {
            get { return Utility.IntNParse(cmbSupplierID.SelectedValue); }
            set
            {
                if (value != null)
                    cmbSupplierID.SelectedValue = value;
                else
                    cmbSupplierID.SelectedValue = DBNull.Value;
            }
        }

        public List<DataRow> ChangedRows
        {
            get { return _changedRow; }
        }

        public override DataTable Table
        {
            get { return _bindingSource.DataSource as DataTable; }
            set
            {
                _bindingSource.DataSource = null;
                _bindingSource.DataSource = value;

                int billCount, doxCount, packCount;
                decimal totalRate, commission;
                OrderENT.CalculateBillCount(_bindingSource.DataSource as DataTable, out billCount, out doxCount, out packCount,
                    out totalRate, out commission);

                lblBillCount.Text = "Số bill: " + billCount;
                lblDoxCount.Text = "Số DOX: " + doxCount;
                lblPackCount.Text = "Số PACK: " + packCount;
                lblTotalRate.Text = Utility.CurrencyParse(totalRate);
                lblCommission.Text = Utility.CurrencyParse(commission);
            }
        }

        #endregion

        #region Public Methods

        public override void Save()
        {
            try
            {
                dtgOrder.EndEdit();
                int rowIndex = dtgOrder.CurrentCell.RowIndex;

                _presenter.Save();
                LoadData<SaleOrderENT>();
                SetMessage("Dữ liệu đã lưu thành công");
                if (dtgOrder.RowCount > 0)
                    dtgOrder.CurrentCell = dtgOrder[colNumber.Index, rowIndex];
            }
            catch (BusinessLogicException ex)
            {
                ShowMessageBoxError(ex.Message);
            }
        }

        public void UpdateFuel()
        {
            UpdateFuelView view = new UpdateFuelView();
            if (view.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                LoadData<SaleOrderENT>();
        }

        #endregion
    }
}
